﻿using System;
using System.Linq;
using System.ComponentModel;

namespace N2.ComponentModel
{
	public class ContentItemTypeDescriptor
		: CustomTypeDescriptor
	{
		#region Constructors

		public ContentItemTypeDescriptor(
				ICustomTypeDescriptor parent,
				ContentItem contentItem)
			: base(parent)
		{
			this.instance = contentItem;
		}
		
		#endregion Constructors

		#region Fields

		protected readonly ContentItem instance;

		#endregion Fields

		public override string GetClassName()
		{
			return instance.GetType().Name;
		}

		public override PropertyDescriptorCollection GetProperties()
		{
			return this.GetProperties(new Attribute[0]);
		}

		public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
		{
			return
				new PropertyDescriptorCollection((
					from _detail in this.instance.Details
					select new { Key = "Details", Value = _detail.Value }
					).Concat(
						from _category in this.instance.DetailCollections
						from _property in _category.Value.Details
						select new { Key = _category.Key, Value = _property }
					).Select(_pair => new ContentItemPropertyDescriptor(
						TypeDescriptor.CreateProperty(
								typeof(ContentItem),
								_pair.Value.Name,
								typeof(string)),
							_pair.Value,
							_pair.Key)
					).ToArray());
		}
	}
}
